<template>
	<div class="flex-sub flex align-center">
		<el-breadcrumb separator="/">
			<el-breadcrumb-item  v-for="(item, index) in levelList" :key="item.path">
				<strong v-if="item.redirect === 'noRedirect' || index == levelList.length - 1" class="no-redirect text-lg text-white">{{ item.meta.title }}</strong>
				<a v-else @click.prevent="handleLink(item)" class="text-lg text-white">{{ item.meta.title }}</a>
			</el-breadcrumb-item>
		</el-breadcrumb>
	</div>
</template>

<script setup>
	import { ref, watch } from 'vue'
	import { compile } from 'path-to-regexp'
	import { useRoute, useRouter } from 'vue-router' //路由
	import { toRaw } from '@vue/reactivity'

	const levelList = ref([])
	const route = useRoute()
	const router = useRouter()

	// 监听当前路由
	watch(() => router.currentRoute.value, (newValue) => {
		getBreadcrumb()
	}, { immediate: true })

	function getBreadcrumb() {
		// only show routes with meta.title
		let matched = route.matched.filter(item => item.meta && item.meta.title)
		const first = matched[0]

		if (!isDashboard(first)) {
			// matched = [{ path: '/dashboard', meta: { title: '首页' } }].concat(matched)
		}

		levelList.value = matched.filter(item => item.meta && item.meta.title && item.meta.breadcrumb !== false)
	}

	function isDashboard(route) {
		const name = route && route.name
		if (!name) {
			return false
		}
		return name.trim().toLocaleLowerCase() === '首页'.toLocaleLowerCase()
	}

	function pathCompile(path) {
		// To solve this problem https://github.com/PanJiaChen/vue-element-admin/issues/561
		const { params } = route
		var toPath = compile(path)
		return toPath(params)
	}

	function handleLink(item) {
		const { redirect, path } = item
		if (redirect) {
			router.push(redirect)
			return
		}
		router.push(this.pathCompile(path))
	}
</script>

<style lang="scss" scoped>

</style>